import axios, { AxiosHeaders, AxiosError } from 'axios'
import type { AxiosResponse, AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios'

// 创建 Axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL || '', // 可根据环境变量配置基础 URL
  timeout: 5000, // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么，例如添加请求头
    const token = localStorage.getItem('token')
    if (token) {
      if (!config.headers) {
        config.headers = new AxiosHeaders()
      }
      config.headers.set('Authorization', `Bearer ${token}`)
    }
    return config
  },
  (error: AxiosError) => {
    // 处理请求错误
    console.error('请求错误:', error)
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    return response.data
  },
  (error) => {
    // 处理响应错误
    const { response = {} } = error
    if (response.status === 401) {
      location.href = './#/login'
      return Promise.reject(error)
    }

    response.data = response.data || {}
    let cont = response.data.msg || error.message
    if (cont === 'Network Error') {
      cont = '后端接口连接异常'
    } else if (cont.includes('timeout')) {
      cont = '系统接口请求超时'
    }
    console.error('响应错误:', error)
    return Promise.reject(error)
  },
)

// 封装请求方法
const request = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    console.log('url', url)
    console.log('url', import.meta.env.VITE_APP_API_URL)
    return service.get(url, config)
  },
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config)
  },
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config)
  },
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config)
  },
}

export default request
